package com.softme.trade.security;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

import com.softme.trade.i18n.I18nUtils;
import com.softme.trade.view.util.FacesUtil;

/**
 * PhaseListener utilizado para capturar excecoes de autenticacao
 * 
 */
@SuppressWarnings({ "serial" })
public class LoginErrorPhaseListener implements PhaseListener
{

	@Override
	public void afterPhase(PhaseEvent arg0)
	{
	}

	@SuppressWarnings({ "unchecked" })
	@Override
	public void beforePhase(PhaseEvent arg0)
	{
		Exception dadosIncorretosException = (Exception) FacesUtil.getSessionMap().get(
				WebAttributes.AUTHENTICATION_EXCEPTION);
		
		if (dadosIncorretosException instanceof BadCredentialsException)
		{
			FacesUtil.getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			//FIXME - Colocar i18N
			FacesUtil.showErrorMessage(I18nUtils.getString("incorrectData"));
		}
	}

	@Override
	public PhaseId getPhaseId()
	{
		return PhaseId.RENDER_RESPONSE;
	}

}
